package ua.com.cms.models;

import com.google.code.morphia.Morphia;
import com.google.code.morphia.dao.BasicDAO;
import com.google.code.morphia.query.Query;
import com.mongodb.Mongo;
import org.bson.types.ObjectId;
import ua.com.cms.entities.Page;
import ua.com.cms.entities.Slot;
import ua.com.cms.entities.Template;

import java.util.ArrayList;
import java.util.List;

public class PageDao extends BasicDAO<Page, ObjectId> {
    public PageDao(Mongo mongo, Morphia morphia, String dbName, String username, String password, boolean isAuthenticated) {
        super(mongo, morphia, dbName);
    }

    public Page findPagebyName(String name){
        Query<Page> query = getDatastore().createQuery(Page.class);
        return query.field("name").equal(name).get();
    }

    public Page findPagebyId(ObjectId id){
        Query<Page> query = getDatastore().createQuery(Page.class);
        return query.field("id").equal(id).get();
    }

    public Page get_or_create(String name, List<ObjectId> templates){
        Page page = findPagebyName(name);
        if(page == null){
            page = new Page();
            page.setName(name);
            page.setTemplates(templates);
            getDatastore().save(page);
        }
        return page;
        
    }

    public void deletePagebyName(String name){
        Query<Page> query = getDatastore().createQuery(Page.class);
        query = query.field("name").equal(name);
        getDatastore().delete(query);
    }

    public void deletePagebyId(ObjectId id){
        Query<Page> query = getDatastore().createQuery(Page.class);
        query = query.field("id").equal(id);
        getDatastore().delete(query);
    }

    public void updatePagebyId(ObjectId currentId, String name, List<ObjectId> templates){
        deletePagebyId(currentId);
        get_or_create(name, templates);
    }

    public void updatePagebyName(String currentName, String name, List<ObjectId> templates){
        deletePagebyName(currentName);
        get_or_create(name, templates);
    }

    public List<Page> getAll(){
    	return getDatastore().find(Page.class).asList();
    }
    
	public List<String> getAllNames() {
        List<Page> allPages = getAll();
        List<String> namesSlots = new ArrayList<String>();
        for (Page page : allPages) {
        	namesSlots.add(page.getName()+" templates:"+page.getTemplates());
		}
        return namesSlots;
	}
}
